//
//  MusicHelper.m
//  JZMCFM
//
//  Created by Mc on 15/11/3.
//  Copyright (c) 2015年 陈卓. All rights reserved.
//

#import "MusicHelper.h"
#import <AVFoundation/AVFoundation.h>

@interface MusicHelper ()
@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)BOOL isPrepare;
@end
@implementation MusicHelper

- (instancetype)init
{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEndAction:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

+ (instancetype)sharedInstance
{
    static MusicHelper *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MusicHelper alloc] init];
    });
    return manager;
}

- (AVPlayer *)player
{
    if (!_player) {
        _player = [[AVPlayer alloc] init];
    }
    return _player;
}

- (void)prepareWithUrl:(NSString *)url
{
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    // 释放观察者
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    // 创建一个观察者
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 根据当前item接环音乐
    [self.player replaceCurrentItemWithPlayerItem:item];
    
}

- (void)play
{
    if (!_isPrepare) {
        return;
    }
    
    [self.player play];
    _isPlaying = YES;
    if (self.timer) {
        return;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
- (void)pause
{
    if (!_isPlaying) {
        return;
    }
    [self.player pause];
    _isPlaying = NO;
    
    [self.timer invalidate];
    self.timer = nil;
}
- (void)stop
{
    if (!_isPlaying) {
        return;
    }
    
    [self.player pause];
    
    [self.player seekToTime:CMTimeMake(0, self.player.currentTime.timescale)];
    
}

- (void)seekToTime:(float)time
{
    [self pause];
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        [self play];
    }];
}

- (void)timerAction:(NSTimer *)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playWithAudioPlayer:withProgress:)]) {
        float progress = self.player.currentTime.value / self.player.currentTime.timescale;
        [self.delegate playWithAudioPlayer:self withProgress:progress];
    }
}

- (void)playEndAction:(NSNotification *)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playEndFinish:)]) {
        [self.delegate playEndFinish:self];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [change[@"new"] integerValue];
        switch (status) {
            case AVPlayerStatusFailed:
            {
                NSLog(@"失败");
                break;
            }
                case AVPlayerStatusReadyToPlay:
            {
                NSLog(@"播放");
                _isPrepare = YES;
                [self play];
                break;
            }
                case AVPlayerStatusUnknown:
            {
                NSLog(@"未知");
                break;
            }
            default:
                break;
        }
    }
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
@end
